package com.zyb.warehouse.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.zyb.warehouse.entity.Auth;
import com.zyb.warehouse.mapper.AuthMapper;
import com.zyb.warehouse.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Description:用户菜单树业务逻辑实现
 */
@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private AuthMapper authMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 根据用户id查询用户权限(菜单)树的业务方法
     *
     * @param userId
     * @return
     */
    public List<Auth> getAuthTreeByUserId(Integer userId) {
        //先从redis中查询缓存,查到的是权限(菜单)树List<Auth>转的json串
        /*String authTreeListJson = redisTemplate.opsForValue().get("authTree:" + userId);
        if (StringUtils.hasText(authTreeListJson)) {
            //将json串转回权限(菜单)树List<Auth>并返回
            List<Auth> authTreeList = JSON.parseArray(authTreeListJson, Auth.class);
            return authTreeList;
        }*/
        //redis中没有查到缓存,从数据库表中查询所有权限(菜单)
        List<Auth> authAllList = authMapper.selectUserAllAuth(userId);
        //将所有权限(菜单)List<Auth>转成权限(菜单)树List<Auth>
        List<Auth> allAuthTree = allAuthToAllAuthTree(authAllList, 0);
        //将权限(菜单)树List<Auth>转成json串并保存到redis
        //redisTemplate.opsForValue().set("authTree:" + userId, JSON.toJSONString(allAuthTree));
        //返回权限(菜单)树List<Auth>
        return allAuthTree;
    }

    //将所有权限(菜单)转成权限(菜单)树的递归算法
    private List<Auth> allAuthToAllAuthTree(List<Auth> allAuthList, Integer pid) {
        List<Auth> firstLevelAuth = new ArrayList<>();
        //获取父权限(菜单)id为参数parentId的所有权限(菜单)
        //parentId最初为0,即最初查的是所有一级权限(菜单)
        for (Auth auth : allAuthList) {
            if (auth.getParentId() == pid) {
                firstLevelAuth.add(auth);
            }
        }
        //查询List<Auth> authList中每个权限(菜单)的所有子级权限(菜单)
        for (Auth auth : firstLevelAuth) {
            List<Auth> childLevelAuth = allAuthToAllAuthTree(allAuthList, auth.getAuthId());
            auth.setChildAuth(childLevelAuth);
        }
        return firstLevelAuth;
    }

    /**
     * 查询所有给角色分配的权限菜单树
     *
     * @return
     */
    public List<Auth> getAllRoleAuthTree() {
        //先查询所有菜单树
        List<Auth> allAuthTree = authMapper.selectAllAuthTree();
        //遍历所有菜单树
        List<Auth> authList = allAuthToAllAuthTree(allAuthTree, 0);
        return authList;
    }
}
